import { defineStore } from "pinia";
import {
  getTableData,
  createTableData,
  removeTableData,
  editeTableData
} from "@/network/table";
import {ListName} from './type'
import { timeFormat } from "@/utils/format";

const useTableStore = defineStore('table', {
  state: () => ({
    usersList: [],
    usersCount: 0,
    rolesList: [],
    rolesCount: 0,
    sportsList: [],
    sportsCount: 0,
    athletesList: [],
    athletesCount: 0,
    collegesList: [],
    collegesCount: 0,
    scoresList: [],
    scoresCount: 0,
    registerList: [],
    registerCount: 0,
    complainsList: [],
    complainsCount: 0,
    checksList: [],
    checksCount: 0,
    currentQuery:{}
  }),
  actions: {
    async getTableAction(listName: string, data: any) {
      this.currentQuery = data
      const res = await getTableData(listName, data)
      this.$patch({
        [`${listName}List`]: res.data.list,
        [`${listName}Count`]:res.data.totalCount
      })
    },
    async createTableAction(listName: string, data: any) {
      if (data.time) {
        data.time = timeFormat(data.time)
      }
      const res = await createTableData(listName, data)
      
      this.getTableAction(listName,{...this.currentQuery})
    },
    async removeTableAction(listName: string, id: number) {
      await removeTableData(listName,id)
      this.getTableAction(listName,{...this.currentQuery})

    },
    async editeTableAction(listName: string, id: number, data: any) {      
      const res = await editeTableData(listName, id, data)
      this.getTableAction(listName,{...this.currentQuery})

    }
  },
  getters: {
    dataList(state) {
      return (listName: ListName) => state[`${listName}List`]
    },
    dataCount(state) {
      return (listName: ListName) => state[`${listName}Count`]
    }
  }
})

export default useTableStore